const http = require("http");
const fs = require("fs");
const path = require("path");

var pagePath = path.join(__dirname, "/index.html");
var iconPath = path.join(__dirname, "/icon.png");

    /**
     * http://localhost:8081/pathname?delId=921&pageId=3
     * '?'后面是传入的id
     * 
     * req.url即（pathname?delId=921&pageId=3）是指端口或者域名之后的部分
     */

function parseUrl(urlStr){
    var index = urlStr.indexOf("?");
    var pathName = "";
    var args = "";
    var argObj = {};

    if(index==-1){ //如果找不到资源路径
        pathName = urlStr;
    }
    else{
        var pathName = urlStr.slice(0, index);// 即例子：http://localhost:8081/
        args = urlStr.slice(index+1); //从?后面的位置开始
        var argArr = args.split("&"); //将数组通过‘&’分割
        
        for(var i=0;i<argArr.length;i++){
            argObj[argArr[i].split("=")[0]]= argArr[i].split("=")[1];
            //数组的第一个元素是属性名，第二个元素是属性值
        }
        console.log(args);
    }
    
    return {
        pathName: pathName,
        argObj: argObj
    }
}

function router(urlObj,req,res){ //req请求对象，res响应对象
    if(urlObj.pathName.indexOf(".png")>0 || urlObj.pathName.indexOf(".jpg")>0){
        urlObj.pathName = "getimgdata";
    }
    switch(urlObj.pathName) {
        case "/":
            showIndex(res);
            break;
        case "getimgdata":
            resImage(res);
            break;
        case "/getlist":
            showList(res);
            break;
        case "/del":
            deleteFile(urlObj.argObj, res);
            break;
    }
}

function showIndex(res){ //将前端index.html响应到浏览器
    var fileContent = fs.readFileSync(pagePath);
    res.writeHead(200, {"Content-Type": "text/html;charset=utf-8"});
    res.write(fileContent);
    res.end();
}

function resImage(res){ //响应图片到浏览器
    var imgContent = fs.readFileSync(iconPath);
    res.writeHead(200, {"Content-Type":"image/png"});
    res.write(imgContent);
    res.end();
}

function createTime(ctimeMs) { //将毫秒转换成年月日时分秒
    var date1 = new Date(ctimeMs);
    var year = date1.getFullYear();
    var month = date1.getMonth() + 1;
    var day = date1.getDate();
    var hour = date1.getHours();
    var minute = date1.getMinutes();
    return year+'-'+month+'-'+day+' '+hour+':'+minute;
}

function showList(res){ //得到文件夹目录的结构
    var dirPath = path.join(__dirname, "/fileDir");
    var files = fs.readdirSync(dirPath);
    var fileList = [];
    for(var i=0; i<files.length; i++){
        var filePath = path.join(dirPath, "/"+files[i]);
        var fileObj = fs.statSync(filePath); //得到fileObj信息
        var obj = {};
        obj.fileName = files[i];
        obj.fileTime = createTime(fileObj.ctimeMs); //获取创建时间
        obj.fileSize = fileObj.size; //获取文件大小
        obj.fileType = fileObj.isFile()?"file":"folder"; //获取文件类型：文件/文件夹
        fileList.push(obj); //添加到数组末尾
    }
    var jsonStr = JSON.stringify(fileList); //将文件夹转成JSON数据
    res.writeHead(200, {"Content-Type": "text/plain"}); //响应一个普通文本
    res.write(jsonStr);
    res.end();
}

function deleteFile(argObj, res){//删除，argObj是点击时获取的ID
    var delId = argObj.delId;
    var dirPath = path.join(__dirname, "/fileDir");
    var files = fs.readdirSync(dirPath);
    for(var i=0; i<files.length; i++){
        var fileObj = fs.statSync(path.join(dirPath,"/"+files[i]));
        if(delId.indexOf(fileObj.ctimeMs) > 0){
            fs.unlinkSync(path.join(dirPath,"/"+files[i]));//删除文件

            res.end("success");
            break;
        }
    }
}

http.createServer((req,res)=>{
    /**
     * http://localhost:8081/pathname?delId=921&pageId=3
     * '?'后面是传入的id
     * 
     * req.url即（pathname?delId=921&pageId=3）是指端口或者域名之后的部分
     */
    var urlStr = req.url;
   
    var urlObj = parseUrl(urlStr);
    

    router(urlObj,req,res);

}).listen(8081);

console.log("server is listening 8081");